package com.his.config;

import com.his.config.annotation.CurrentUser;
import com.his.login.entity.DictEmployee;
import com.xiao.common.exception.HisExecption;
import com.xiao.common.service.SessionService;
import com.xiao.common.util.ResultUtil;
import org.hibernate.Session;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author xiaoxiaoping
 * @Date 2020/2/4 13:42
 * @Version 1.0
 */
@Component
public class CurrentUserHandlerMethodArgReslover implements HandlerMethodArgumentResolver {
    @Resource
    SessionService sessionService;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterAnnotation(CurrentUser.class) != null && methodParameter.getParameterType() == DictEmployee.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            if(null == sessionService.getSessionUser(token)){
                throw HisExecption.paramException("请登录");
            }
            return  (DictEmployee)sessionService.getSessionUser(token);
        }else{
           throw HisExecption.paramException("请登录");
        }
    }
}
